package org.jeecg.modules.wlhy.order.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.hyproject.service.IHyProjectService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.entity.HyOrderDriver;
import org.jeecg.modules.wlhy.order.service.IHyOrderDriverService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: hy_order_driver
 * @Author: jeecg-boot
 * @Date:   2021-05-13
 * @Version: V1.0
 */
@Api(tags="hy_order_driver")
@RestController
@RequestMapping("/order/hyOrderDriver")
@Slf4j
public class HyOrderDriverController extends JeecgController<HyOrderDriver, IHyOrderDriverService> {
	@Autowired
	private IHyOrderDriverService hyOrderDriverService;
	 @Autowired
	 private UserUtil userUtil;

	 @Autowired
	 private IHyOrderService hyOrderService;

	 @Autowired
	 private IHyProjectService hyProjectService;

	@ApiOperation(value="hy_order_driver-分页列表查询", notes="hy_order_driver-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyOrderDriver hyOrderDriver,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyOrderDriver> queryWrapper = QueryGenerator.initQueryWrapper(hyOrderDriver, req.getParameterMap());


		Page<HyOrderDriver> page = new Page<HyOrderDriver>(pageNo, pageSize);
		IPage<HyOrderDriver> pageList = hyOrderDriverService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	 @ApiOperation(value="hy_order_driver-分页列表查询", notes="hy_order_driver-分页列表查询")
	 @GetMapping(value = "/customerlist")
	 public Result<?> customerlist(HyOrderDriver hyOrderDriver,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<HyOrderDriver> queryWrapper = QueryGenerator.initQueryWrapper(hyOrderDriver, req.getParameterMap());
//		 HyCustomer customer = userUtil.getCustomer();
//		 if(customer==null){
//			 return Result.error("未找到货主信息！");
//		 }
//		 queryWrapper.eq("customer_id",customer.getId());
		 Page<HyOrderDriver> page = new Page<HyOrderDriver>(pageNo, pageSize);
		 IPage<HyOrderDriver> pageList = hyOrderDriverService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	@AutoLog(value = "hy_order_driver-添加")
	@ApiOperation(value="hy_order_driver-添加", notes="hy_order_driver-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody HyOrderDriver hyOrderDriver) {
		if(StringUtils.isEmpty(hyOrderDriver.getOrderId())){
			return Result.error("货源不能为空！");
		}
		if(StringUtils.isEmpty(hyOrderDriver.getDriverId())){
			return Result.error("司机不能为空！");
		}
		HyCustomer customer = userUtil.getCustomer();
		if(customer==null){
			return Result.error("未找到货主！");
		}
		HyOrderDriver one = hyOrderDriverService.getOne(new QueryWrapper<HyOrderDriver>()
				.eq("order_id", hyOrderDriver.getOrderId())
				.eq("driver_id", hyOrderDriver.getDriverId())
				.eq("customer_id", customer.getId())
		);
		if(one!=null){
			return Result.error("不能重复添加！");
		}
		hyOrderDriver.setCustomerId(customer.getId());
		hyOrderDriverService.save(hyOrderDriver);
		return Result.OK("添加成功！");
	}


	 @PostMapping(value = "/addByDriverIds")
//	 public Result<?> addByIds(@RequestBody HyOrderDriver hyOrderDriver) {
	 public Result<?> addByIds(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
		 String orderId = jsonObject.getString("orderId");
		 if (StringUtils.isEmpty(orderId)) {
			 return Result.error("货源不能为空！");
		 }
		 String driverIds = jsonObject.getString("driverIds");
		 if (StringUtils.isEmpty(driverIds)) {
			 return Result.error("司机不能为空！");
		 }
		 HyOrder oldorder = hyOrderService.getById(orderId);
		 if(oldorder == null){
			 return Result.error("货源信息不存在");
		 }
		 HyCustomer customer = null;
		 if(userUtil.isSys()){
			 String customerId = oldorder.getCustomerId();
			 if(StringUtils.isEmpty(customerId)){
				 return Result.error("货主信息不存在");
			 }
			 customer = userUtil.getCustomerById(customerId);
			 if(customer == null){
				 return Result.error("货主信息不存在");
			 }
		 }else {
			 customer = userUtil.getCustomer();
		 }
		 if(customer == null){
			 return Result.error("货主信息不存在");
		 }
		 List<String> ids = Arrays.asList(driverIds.split(","));
		 List<HyOrderDriver> orderDrivers1 = hyOrderDriverService.list(
		 		new QueryWrapper<HyOrderDriver>()
				.eq("order_id", orderId)
				.eq("customer_id", customer.getId()).in("driver_id",ids)
		 );
		 List<String> newids = new ArrayList<>();
		 //过滤已经添加过的司机
		 for (String driverId : ids) {
		 	 boolean ishave = false;
			 for (HyOrderDriver hyOrderDriver : orderDrivers1) {
				 if(StringUtils.equals(driverId,hyOrderDriver.getDriverId())){
					 ishave = true;
				 	break;
				 }
			 }
			 if(!ishave){
				 newids.add(driverId);
			 }
		 }
		 if(newids.size()==0){
			 return Result.OK("添加成功！");
		 }
		 List<HyOrderDriver> orderDrivers = new ArrayList<>();
		 for (String driverId : newids) {
			 HyOrderDriver hyOrderDriver = new HyOrderDriver();
			 hyOrderDriver.setDriverId(driverId);
			 hyOrderDriver.setOrderId(orderId);
			 hyOrderDriver.setCustomerId(customer.getId());
			 orderDrivers.add(hyOrderDriver);
		 }
		 hyOrderDriverService.saveBatch(orderDrivers);
		 return Result.OK("添加成功！");
	 }

	/**
	 *  编辑
	 *
	 * @param hyOrderDriver
	 * @return
	 */
	@AutoLog(value = "hy_order_driver-编辑")
	@ApiOperation(value="hy_order_driver-编辑", notes="hy_order_driver-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HyOrderDriver hyOrderDriver) {
		hyOrderDriverService.updateById(hyOrderDriver);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "hy_order_driver-通过id删除")
	@ApiOperation(value="hy_order_driver-通过id删除", notes="hy_order_driver-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		if (!userUtil.isSys()) {
			HyCustomer customer = userUtil.getCustomer();
			if (customer == null) {
				return Result.error("未找到货主！");
			}
			HyOrderDriver orderDriver = hyOrderDriverService.getById(id);
			if(orderDriver == null){
				return Result.error("数据不存在！");
			}
			if(!StringUtils.equals(orderDriver.getCustomerId(), customer.getId())){
				return Result.error("信息错误！");
			}
		}

		hyOrderDriverService.removeById(id);
		return Result.OK("删除成功!");
	}

//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "hy_order_driver-批量删除")
//	@ApiOperation(value="hy_order_driver-批量删除", notes="hy_order_driver-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyOrderDriverService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */

	@ApiOperation(value="hy_order_driver-通过id查询", notes="hy_order_driver-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HyOrderDriver hyOrderDriver = hyOrderDriverService.getById(id);
		if(hyOrderDriver==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hyOrderDriver);
	}

//    /**
//    * 导出excel
//    *
//    * @param request
//    * @param hyOrderDriver
//    */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, HyOrderDriver hyOrderDriver) {
//        return super.exportXls(request, hyOrderDriver, HyOrderDriver.class, "hy_order_driver");
//    }
//
//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, HyOrderDriver.class);
//    }

}
